﻿using Cloud.Update.Core.Extends;
using Cloud.Update.Core.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Cloud.Update.Core.Utils
{
    public class Validate
    {
        public static void ValidateClientParameter(ClientParameter clientParameter) {

            if (!clientParameter.IsRestore)
            {
                if (string.IsNullOrEmpty(clientParameter.DownLoadPath)) throw new NullReferenceException("安装路径不能为空!");

                if (string.IsNullOrEmpty(clientParameter.UnZipPath))
                    clientParameter.UnZipPath = clientParameter.DownLoadPath;
                if (string.IsNullOrEmpty(clientParameter.AppName)) throw new NullReferenceException("启动程序名称不能为空!");

                if (clientParameter.UpdateVersions == null || clientParameter.UpdateVersions.Count <= 0) throw new NullReferenceException("更新数组不能为空!");

                if (clientParameter.UpdateVersions.Any(x => string.IsNullOrEmpty(x.Url))) throw new NullReferenceException("更新数组中的更新地址不能为空!");
            }
            else { 
                if(!File.Exists(clientParameter.BackUpPath + @"\version.ini")) throw new NullReferenceException("无法还原程序至上一个版本,因为"+ clientParameter.BackUpPath + @"\version.ini不存在,找不到还原切入点!");
                DirectoryInfo directInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);//获取文件

                var currentVersion = VersionExtension.Read("versions", "current_version", null, clientParameter.BackUpPath + @"\version.ini");
                var oldVersion = VersionExtension.Read("versions", "current_version", null, directInfo.Parent.FullName + @"\version.ini");
                if (currentVersion.Equals(oldVersion)) {
                    throw new NullReferenceException("目标还原版本与当前版本一致,不需要还原或是已经还原!");
                }
            }
        }
    }
}
